<template>
  <div style="display: block; width: 40%">
    <div class="block">
      <el-tree
        :data="data"
        show-checkbox
        node-key="id"
        :default-expand-all="false"
        :expand-on-click-node="false"
        :render-content="renderContent"
      >
      </el-tree>
    </div>
  </div>
</template>
<script>
import { itemTreeList } from "@/api/itemcat";
let id = 1000;

export default {
  data() {
    return {
      data: [],
    };
  },
  created() {
    this.list();
  },

  methods: {
    list() {
      itemTreeList().then((result) => {
        this.data = result.data.data;
      });
    },
    append(data) {
      const newChild = { id: id++, label: "testtest", children: [] };
      if (!data.children) {
        this.$set(data, "children", []);
      }
      data.children.push(newChild);
    },

    remove(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex((d) => d.id === data.id);
      children.splice(index, 1);
    },

    renderContent(h, { node, data, store }) {
      console.log(node);
      return (
        <span class="custom-tree-node">
          <span>{node.data.name}</span>
          <span>
            {node.level < 3 ? (
              <el-button
                size="mini"
                type="text"
                on-click={() => this.append(data)}
              >
                添加
              </el-button>
            ) : (
              ""
            )}
            <el-button
              size="mini"
              type="text"
              on-click={() => this.remove(node, data)}
            >
              删除
            </el-button>
            <el-button
              size="mini"
              type="text"
              on-click={() => this.remove(node, data)}
            >
              修改
            </el-button>
          </span>
        </span>
      );
    },
  },
};
</script>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
